<template>
  <div class="container">
    <div class="content-wrapper">
      <!-- 音频播放器 -->
      <audio-player :input-text="currentWord" @play-end="handlePlayEnd" ref="audioPlayerRef" />

      <!-- 骨架屏 -->
      <div v-if="isLoading" class="skeleton-container">
        <el-skeleton animated :count="1">
          <template #template>
            <div style="padding: 14px">
              <el-skeleton-item variant="image" style="width: 100%; height: 240px" />
              <div style="display: flex; align-items: center; margin-top: 8px">
                <el-skeleton-item variant="text" style="margin-right: 16px; width: 100px" />
                <el-skeleton-item variant="text" style="width: 50%" />
              </div>
            </div>
          </template>
        </el-skeleton>
      </div>

      <!-- 图片展示和选择 -->
      <div v-else class="image-selection">
        <div class="grid-container">
          <div
            v-for="(img, index) in galleryImages"
            :key="img.url"
            class="image-card"
            :class="{
              'is-selected': selectedImageIndex === index,
              'is-correct': hasAnswered && index === correctImageIndex,
              'is-incorrect':
                hasAnswered && selectedImageIndex === index && index !== correctImageIndex,
            }"
            @click="handleImageSelect(index)"
          >
            <div class="image-wrapper">
              <img :src="img.url" />
              <!--<div v-if="img.caption" class="image-caption">{{ img.caption }}</div>-->
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-area" v-if="!hasAnswered">
          <el-button type="primary" :disabled="selectedImageIndex === null" @click="checkAnswer">
            确认答案
          </el-button>
        </div>

        <!-- 答案反馈 -->
        <div v-if="hasAnswered" class="feedback-area">
          <el-alert
            :title="feedbackMessage"
            :type="isCorrectAnswer ? 'success' : 'error'"
            :closable="false"
            show-icon
            class="feedback-message"
          />

          <!-- 正确时的倒计时 -->
          <div class="countdown" v-if="isCorrectAnswer">将在 {{ countdown }} 秒后继续...</div>

          <!-- 错误时的重试按钮 -->
          <div class="retry-area" v-if="!isCorrectAnswer">
            <el-button type="primary" @click="resetAnswer"> 重新选择 </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import AudioPlayer from '@/components/AudioPlayer.vue'
import type { Word } from '@/types/training'

interface ImageData {
  url: string
  alt: string
  aspectRatio: string
  caption: string
  isCorrect: boolean
}

interface Props {
  audio: {
    words: Word[]
  }
  images: {
    words: Word[]
  }
}

const props = withDefaults(defineProps<Props>(), {
  audio: () => ({
    words: [] as Word[],
  }),
  images: () => ({
    words: [] as Word[],
  }),
})

const emit = defineEmits<{
  (e: 'complete'): void
}>()

// 状态管理
const currentWord = ref(props.audio.words[0].text || '')
const galleryImages = ref<ImageData[]>([])
const isLoading = ref(false)
const audioPlayerRef = ref<InstanceType<typeof AudioPlayer> | null>(null)
const selectedImageIndex = ref<number | null>(null)
const hasAnswered = ref(false)
const correctImageIndex = ref<number>(0) // 假设第一张图片是正确答案

// 计算属性
const isCorrectAnswer = computed(() => {
  return selectedImageIndex.value === correctImageIndex.value
})

const feedbackMessage = computed(() => {
  return isCorrectAnswer.value ? '回答正确！' : '回答错误！'
})

// 获取对应单词的图片
const fetchImages = async () => {
  if (props.images.words.length === 0) return

  isLoading.value = true
  try {
    // 并行获取所有单词的图片
    const imagePromises = props.images.words.map(async (word) => {
      const response = await axios.post(`/api/pic/getUrl?prompt=${encodeURIComponent(word.text)}`)
      // 只取第一张图片
      const imageData = response.data[0] || {}
      return {
        url: imageData.url,
        alt: imageData.alt || word.text,
        aspectRatio: imageData.aspectRatio || '1/1',
        caption: imageData.caption || word.text,
        isCorrect: word.isCorrect || false,
      }
    })

    const images = await Promise.all(imagePromises)
    galleryImages.value = images

    // 找到正确答案的索引
    const correctIndex = images.findIndex((img) => img.isCorrect)
    correctImageIndex.value = correctIndex >= 0 ? correctIndex : 0
  } catch (error) {
    console.error('获取图片失败:', error)
    galleryImages.value = []
    ElMessage.error('获取图片失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 处理图片选择
const handleImageSelect = (index: number) => {
  if (!hasAnswered.value) {
    selectedImageIndex.value = index
  }
}

// 状态管理 - 添加倒计时
const countdown = ref(2)
const resetTimer = ref<number | null>(null)
// 重置答案状态
const resetAnswer = () => {
  hasAnswered.value = false
  selectedImageIndex.value = null
  if (resetTimer.value) {
    clearInterval(resetTimer.value)
    resetTimer.value = null
  }
  countdown.value = 2 // 重置倒计时
}

// 检查答案
const checkAnswer = () => {
  if (selectedImageIndex.value === null) return
  hasAnswered.value = true

  // 只有正确答案需要倒计时
  if (isCorrectAnswer.value) {
    resetTimer.value = window.setInterval(() => {
      countdown.value -= 1
      if (countdown.value <= 0) {
        resetAnswer() // 先清除状态
        emit('complete') // 再触发跳转
      }
    }, 1000)
  }
}

// 处理音频播放结束
const handlePlayEnd = () => {
  // 音频播放结束后不自动触发complete，等待用户选择答案
}

// 初始化加载
onMounted(async () => {
  if (currentWord.value) {
    await fetchImages()
    // 自动播放第一个音频
    if (audioPlayerRef.value && 'play' in audioPlayerRef.value) {
      ;(audioPlayerRef.value as { play: () => void }).play()
    }
  }
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (resetTimer.value) {
    clearInterval(resetTimer.value)
  }
})
</script>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  padding: 12px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content-wrapper {
  width: 100%;
  max-width: 800px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.skeleton-container {
  background: #fff;
  border-radius: 12px;
  padding: 12px;
  margin-top: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.image-selection {
  margin-top: 12px;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 16px;
  padding: 0 4px;
}

.image-card {
  cursor: pointer;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.image-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.image-card.is-selected {
  border-color: var(--el-color-primary);
}

.image-card.is-correct {
  border-color: var(--el-color-success);
}

.image-card.is-incorrect {
  border-color: var(--el-color-danger);
}

.image-wrapper {
  position: relative;
  aspect-ratio: 1/1;
}

.image-wrapper img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 8px;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: white;
  font-size: 13px;
  text-align: center;
  font-weight: 500;
}

.submit-area {
  display: flex;
  justify-content: center;
  margin-top: 16px;
  padding: 0 16px;
}

.submit-area .el-button {
  width: 100%;
  max-width: 300px;
  height: 44px;
  font-size: 16px;
  border-radius: 22px;
}

.feedback-area {
  margin-top: 1.5rem;
  padding: 0 16px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.feedback-message {
  margin-bottom: 8px;
}

.feedback-message :deep(.el-alert) {
  border-radius: 12px;
  padding: 12px 16px;
}

/* iPhone 特定样式 */
@supports (-webkit-touch-callout: none) {
  .container {
    padding-bottom: env(safe-area-inset-bottom);
  }

  .submit-area {
    padding-bottom: env(safe-area-inset-bottom);
  }

  .image-card {
    -webkit-tap-highlight-color: transparent;
  }

  .feedback-area {
    padding-bottom: env(safe-area-inset-bottom);
  }
}

/* 横屏模式 */
@media screen and (orientation: landscape) {
  .grid-container {
    grid-template-columns: repeat(4, 1fr);
  }
}

/* 小屏幕设备 */
@media screen and (max-width: 375px) {
  .grid-container {
    gap: 8px;
  }

  .image-caption {
    font-size: 12px;
    padding: 6px;
  }
}
</style>
